package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 李旭
 * @create: 2021-07-23 14:11
 **/
@RestController
@RequestMapping("/api/order")
public class OrderApiController {


    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderInfoService orderInfoService;

    //查询结算页面
    @GetMapping("/trade")
    public Map<String, Object> trade(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        Map<String, Object> result = new HashMap<>();

        //1:查询收货地址
        List<UserAddress> userAddressList = userFeignClient.getUserAddressList();
        result.put("userAddressList", userAddressList);
        //2:商品清单
        List<CartInfo> cartInfoCheckedList = cartFeignClient.getCartInfoCheckedList();
        //商品清单
        List<OrderDetail> orderDetailList = cartInfoCheckedList.stream()
                .map(cartInfo -> {
                    OrderDetail orderDetail = new OrderDetail();
                    //skuId
                    orderDetail.setSkuId(cartInfo.getSkuId());
                    orderDetail.setSkuName(cartInfo.getSkuName());
                    orderDetail.setImgUrl(cartInfo.getImgUrl());
                    orderDetail.setOrderPrice(cartInfo.getSkuPrice());
                    orderDetail.setSkuNum(cartInfo.getSkuNum());
                    return orderDetail;
                }).collect(Collectors.toList());
        result.put("detailArrayList", orderDetailList);
        //3:商品总件数 12 23 34 56
        long sum = orderDetailList.stream().collect(Collectors.summarizingInt(
                OrderDetail::getSkuNum)).getSum();
        result.put("totalNum", sum);
        //4:总金额
       /* double totalPrice = orderDetailList.stream().collect(Collectors.
                summarizingDouble(orderDetail -> {
                    return orderDetail.getSkuNum() * orderDetail.getOrderPrice().doubleValue();
                })).getSum();*/
        BigDecimal totalPrice = new BigDecimal("0");
        for (OrderDetail orderDetail : orderDetailList) {
            totalPrice = totalPrice.add(orderDetail.getOrderPrice().multiply(new BigDecimal(orderDetail.getSkuNum())));
        }
        result.put("totalAmount", totalPrice);
        //5:订单号 交易号 （防止重复提交）  幂等性
        String tradeNo = UUID.randomUUID().toString();
        //String tradeNo = "atguigu" + System.currentTimeMillis() + new Random().nextInt(1000);
        redisTemplate.opsForValue().set("tradeNo:" + userId,tradeNo);
        result.put("tradeNo", tradeNo);
        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(String tradeNo, @RequestBody OrderInfo orderInfo,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1:防止重复提交
        Object o = redisTemplate.opsForValue().get("tradeNo:" + userId);
        if(null == o || !o.equals(tradeNo)){
            return Result.fail().message("订单已提交");
        }
        redisTemplate.delete("tradeNo:" + userId);
        //2:校验 库存
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            //查询当前商品是否有货
            boolean flag = orderInfoService.isHave(orderDetail);
            if(!flag){
                return Result.fail().message(orderDetail.getSkuName() + "【缺货】");
            }
        }

        //3:提交订单  订单表  订单详情表 删除购物车中已经提交的商品
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.saveOrder(orderInfo);
        return Result.ok(orderId);
    }


    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }
    //拆单   由库存系统发起的
    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId,String wareSkuMap){
        //1：拆单
        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);//
        //2：将多张订单转成发回库存系统的数据
        List<Map> listMap = orderInfoList.stream().map(orderInfo -> {
            return orderInfoService.initWareData(orderInfo);
        }).collect(Collectors.toList());
        return JSONObject.toJSONString(listMap);
    }
}
